// Copyright Epic Games, Inc. All Rights Reserved.

#include "GameFeatureAction_WorldActionBase.h"

#include "Engine/GameInstance.h"
#include "Engine/World.h"

#include UE_INLINE_GENERATED_CPP_BY_NAME(GameFeatureAction_WorldActionBase) // 包含自动生成的代码

/**
 * 游戏特性激活时调用
 */
void UGameFeatureAction_WorldActionBase::OnGameFeatureActivating(FGameFeatureActivatingContext& Context)
{
	GameInstanceStartHandles.FindOrAdd(Context) = FWorldDelegates::OnStartGameInstance.AddUObject(this,  // 查找或添加游戏实例开始句柄
		&UGameFeatureAction_WorldActionBase::HandleGameInstanceStart, FGameFeatureStateChangeContext(Context)); // 绑定到处理函数

	// 添加到任何已初始化且有关联游戏实例的世界
	for (const FWorldContext& WorldContext : GEngine->GetWorldContexts()) // 遍历世界上下文
	{
		if (Context.ShouldApplyToWorldContext(WorldContext)) // 检查是否应应用到世界上下文
		{
			AddToWorld(WorldContext, Context); // 添加到世界
		}
	}
}

/**
 * 游戏特性停用时调用
 */
void UGameFeatureAction_WorldActionBase::OnGameFeatureDeactivating(FGameFeatureDeactivatingContext& Context)
{
	FDelegateHandle* FoundHandle = GameInstanceStartHandles.Find(Context); // 查找句柄
	if (ensure(FoundHandle)) // 确保句柄有效
	{
		FWorldDelegates::OnStartGameInstance.Remove(*FoundHandle); // 移除游戏实例开始委托
	}
	
}

/**
 * 处理游戏实例开始的方法
 */
void UGameFeatureAction_WorldActionBase::HandleGameInstanceStart(UGameInstance* GameInstance, FGameFeatureStateChangeContext ChangeContext)
{
	if (FWorldContext* WorldContext = GameInstance->GetWorldContext()) // 获取世界上下文
	{
		if (ChangeContext.ShouldApplyToWorldContext(*WorldContext)) // 检查是否应应用到世界上下文
		{
			AddToWorld(*WorldContext, ChangeContext); // 添加到世界
		}
	}
}